package ctx

import (
	"strings"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// Context ext content struct
type Context struct {
	*gin.Context
}

// HandlerFunc HandlerFunc
type HandlerFunc func(*Context)

// Handler ext gin.content
func Handler(h HandlerFunc) gin.HandlerFunc {
	return func(c *gin.Context) {
		context := new(Context)
		context.Context = c
		h(context)

	}
}

//Prepare router middleware
func Prepare(list map[string]int, sessionkey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		uri := strings.Split(strings.Split(c.Request.RequestURI, "?")[0], "/")[3]
		if _, inlist := list[uri]; !inlist {
			session := sessions.Default(c)
			user := session.Get(sessionkey)
			if user == nil {
				c.JSON(200, gin.H{
					"status": 401,
				})
				c.Abort()
				return
			}
		}
		c.Next()
	}
}

// Cors 跨域设置
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		Origin := c.Request.Header.Get("Origin")
		// if Origin == "http://mhs.qhxc68.com" || Origin == "http://localhost" {
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Allow-Origin", Origin)                           //header的类型
		c.Header("Access-Control-Allow-Headers", "Content-Type,X-Requested-With") //header的类型
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")            //允许post访问
		// 处理请求
		c.Next() //  处理请求
	}
}
